//
//  YDEmoticonView.swift
//  weibo
//
//  Created by 孙亚东 on 16/7/2.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit


let YDEmoticonNotification = "YDEmoticonNotification"

let YDEmoticonCollectionViewIdentify = "YDEmoticonCollectionViewIdentify"

class YDEmoticonView: UIView {
    

    override init(frame: CGRect) {
        let frame = CGRectMake(0, 0, screenWidth, 216)
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
        
    
    }
    
    func setupUI(){
    
    backgroundColor = UIColor.redColor()

        
        addSubview(emoticonCollectionView)
        addSubview(emoticonToolBar)
        
        
        // 设置frame
        
        emoticonToolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(44.0)
            
            
        }
   
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.left.right.top.equalTo(self)
            
            make.bottom.equalTo(emoticonToolBar.snp_top)
            
            
        }
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonBtnClick:", name: YDEmoticonNotification, object: nil)
        
        
        //设置uicollectionView的item
         setupCollectionItem()


    }
    
    
//MARK: 实现通知方法
    
    func emoticonBtnClick (noti: NSNotification) {
        
        guard let button = noti.userInfo?["emoticon"] else {
        
        
            return
        
        }

        let btn = button as! YDEmoticonButton
        
        if YDEmoticonManager.recentArr.contains(btn.emoticonModel!){
        
            return
            
        }else {

            YDEmoticonManager.recentArr.insert(btn.emoticonModel!, atIndex: 0)
        }

        
        if YDEmoticonManager.recentArr.count > 20 {
        
            YDEmoticonManager.recentArr.removeLast()
        
        }
        
//        emoticonCollectionView.reloadData()
    
    
    }
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
    
        flowLayout.itemSize = CGSizeMake(screenWidth, emoticonCollectionView.bounds.height)
        
        
    }
    
    
    
    func setupCollectionItem() {
    
        emoticonCollectionView.dataSource = self
        
//        emoticonCollectionView.
        
        //注册collectionView
        emoticonCollectionView.registerClass(YDEmoticonCollectionCell.self, forCellWithReuseIdentifier: YDEmoticonCollectionViewIdentify)
        
        emoticonCollectionView.pagingEnabled = true
        
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        flowLayout.scrollDirection = .Horizontal
        
        emoticonCollectionView.showsHorizontalScrollIndicator = false
        emoticonCollectionView.showsVerticalScrollIndicator = false
        
        
        //当初始化的时候，移动到第一

        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.025)), dispatch_get_main_queue()) { () -> Void in
            
            let path = NSIndexPath(forItem: 0, inSection: 1)
            self.emoticonCollectionView.scrollToItemAtIndexPath(path, atScrollPosition: .Left, animated: false)
            
            
        }
        
    
    }
    //懒加载控件

    // 设置流水布局
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    // UICollectionView
    private lazy var emoticonCollectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)

    
    lazy  var emoticonToolBar: YDEmoticonToolBarView = {
        
        let toolBar = YDEmoticonToolBarView(frame: CGRectZero)
        
        toolBar.delegate = self
        
        toolBar.backgroundColor = UIColor.greenColor()
        
        return toolBar
    
    
    }()
    

}





//toolBar按钮的点击代理方法
extension YDEmoticonView: YDEmoticonToolBarViewProtocol {

    func buttonClikDelegate(btn: UIButton) {
        
        print(btn.tag)
        
        switch btn.tag {
        
        case 1000:
            
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
        emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            
        case 1001:
            let indexPath1 = NSIndexPath(forItem: 0, inSection: 1)
            emoticonCollectionView.scrollToItemAtIndexPath(indexPath1, atScrollPosition: .Left, animated: false)
            
        case 1002:
            let indexPath2 = NSIndexPath(forItem: 0, inSection: 2)
            emoticonCollectionView.scrollToItemAtIndexPath(indexPath2, atScrollPosition: .Left, animated: false)
            
        case 1003:
            let indexPath3 = NSIndexPath(forItem: 0, inSection: 3)
            emoticonCollectionView.scrollToItemAtIndexPath(indexPath3, atScrollPosition: .Left, animated: false)
        default:
            break
            
        }
        
    }

}


extension YDEmoticonView: UICollectionViewDataSource {
    
    
    //实现数据源代理方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return YDEmoticonManager.getArray().count
        
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return YDEmoticonManager.getArray()[section].count
        
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YDEmoticonCollectionViewIdentify, forIndexPath: indexPath) as!YDEmoticonCollectionCell
        
        cell.backgroundColor = RandomColor()
        
        let tempArray = YDEmoticonManager.getArray()[indexPath.section]
        
        cell.emoticonArr = tempArray[indexPath.item]
    
        return cell
        
        
    }
  
}




//自定义cell

protocol YDEmoticonCollectionCellProtocol : NSObjectProtocol {


    func  addbuttonToDefault (button: YDEmoticonButton)


}



class YDEmoticonCollectionCell: UICollectionViewCell {
    
    
//    var delegate: YDEmoticonCollectionCellDelegate?
    
    //定义一个数组，接收模型，给btn赋值
    
    var emoticonArr: [YDEmoticonModels]? {
    
        didSet {
            
            guard let emoticonArr = emoticonArr else {
            
            
                return
            
            }
           
            
            //对数组进行遍历
            for button in btnArr {
            
            
                button.hidden = true
            
            }
            
            
            for (index, emoticon) in emoticonArr.enumerate() {
            
                let button = btnArr[index]
                
                button.emoticonModel = emoticon
                
                button.hidden = false
                
            
            }

        }
    
    }

    
    
    
    //创建一个数组用于保存按钮
    var btnArr: [YDEmoticonButton] = [YDEmoticonButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
            addButton(20)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

  
    }

    
    func addButton (btnCount: Int) {
        
        let itemWidth: CGFloat = bounds.size.width / 7.0
        
        let itemHeight: CGFloat = bounds.size.height / 3.0
     
        for i in 0..<20 {
        
            let btn = YDEmoticonButton(type: UIButtonType.Custom)
            
            self.contentView.addSubview(btn)
            
            btnArr.append(btn)
            
            //表情按钮点击方法
            btn.addTarget(self, action: "emoticonBtnClick:", forControlEvents: .TouchUpInside)
            
            
            
        }
        

        self.contentView.addSubview(deleteBtn)
        
        deleteBtn.frame = CGRectMake(self.bounds.width - itemWidth , self.bounds.height - itemHeight, itemWidth, itemHeight)

    
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()

       let itemW: CGFloat = bounds.size.width / 7.0
        
       let itemH: CGFloat = bounds.size.height / 3.0
     
        //遍历数组，进行添加button
        
        for (index,button) in btnArr.enumerate() {
            
            //列号
            let collNum = index % 7
            
            //行号
            let rowNum = index / 7
            
            button.frame = CGRectMake(CGFloat(collNum) * itemW, CGFloat(rowNum) * itemH, itemW, itemH)
            

        }
   
    }
    

//懒加载删除按钮
    lazy var deleteBtn: UIButton = {
    
        let Btn = UIButton(type: UIButtonType.Custom)
        
        Btn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        Btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        
        //添加点击方法
        
         Btn.addTarget(self, action: "deleteEmoticon", forControlEvents: .TouchUpInside)
        
        return Btn
    
        
    }()
    
    
    
    @objc  func deleteEmoticon () {
        
    
        print("删除表情")
        
        
        
    }
    
    @objc  func emoticonBtnClick (button: YDEmoticonButton) {
        
        
        // 利用通知发送数据
    NSNotificationCenter.defaultCenter().postNotificationName(YDEmoticonNotification, object: nil, userInfo: ["emoticon": button])
        
        
        
        
        
        
    }


}









